package com.vhall.component.plugin.common.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.plugin.common.exception.BizErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.util.Objects;

/**
 * @author yongzheng.xu
 * @date 2021/4/25 13:02
 */
@Slf4j
public class UploadUtil {

    private UploadUtil() {
        throw new IllegalStateException("Utility class");
    }

    public static File upload(String name, String path, byte[] file) {

        File dest = null;
        try {
            String fpath = "/tmp/";
            if (!StringUtils.isEmpty(path)) {
                fpath = path;
            }
            if (!FileUtil.exist(path)) {
                FileUtil.mkdir(path);
            }

            OutputStream os = new FileOutputStream(fpath + name);
            IoUtil.write(os, true, file);
            dest = FileUtil.file(fpath + name);
        } catch (IOException e) {
            log.error("上传失败:", e);
        }
        return dest;
    }

    public static File upload(MultipartFile file, String path, String name) {
        if (null == file) {
            return null;
        }
        File dest = null;
        try {
            String fpath = FileUtil.getTmpDirPath();
            String fname = file.getOriginalFilename();
            if (!StringUtils.isEmpty(path)) {
                fpath = path;
            }
            if (!FileUtil.exist(fpath)) {
                FileUtil.mkdir(fpath);
            }
            if (StringUtils.isNoneEmpty(name)) {
                fname = name;
            }
            String rpath = CharSequenceUtil.removeSuffix(fpath, File.separator) + File.separator + fname;
            log.warn("文件上传->{}", rpath);
            FileUtil.writeFromStream(file.getInputStream(), rpath);
            dest = FileUtil.file(rpath);

        } catch (IOException e) {
            log.error("文件上传失败:", e);
        }
        return dest;
    }


    public static File multipartFile2File(MultipartFile file) {

        File toFile = null;
        try {
            if (file.getSize() <= 0) {
                return null;
            }
            InputStream ins = file.getInputStream();
            toFile = new File(Objects.requireNonNull(file.getOriginalFilename()));
            inputStreamToFile(ins, toFile);
            ins.close();
        } catch (Exception ex) {
            log.error("上传失败:", ex);
        }
        return toFile;

    }

    public static InputStream multipartFile2InputStream(MultipartFile file) {
        try {
            byte[] byteArr = file.getBytes();
            return new ByteArrayInputStream(byteArr);
        } catch (Exception ex) {
            log.error("MultipartFile 转 InputStream失败 :", ex);
            throw new BusinessException(BizErrorCode.EMPTY_FILE_CHANGE_ERROR);
        }

    }

    public static void inputStreamToFile(InputStream ins, File file) {
        try (OutputStream os = new FileOutputStream(file)) {

            int bytesRead;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            ins.close();
        } catch (Exception e) {
            log.error("", e);
        }
    }

    /**
     * 删除本地临时文件
     *
     * @param file
     */
    public static void delTmpFile(File file) throws IOException {
        if (file != null) {
            Files.delete(file.toPath());
        }
    }

}
